package com.hobobe.tiercel.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.hobobe.tiercel.common.datasource.CustAnnotation;
import com.hobobe.tiercel.common.datasource.CustomerContextHolder;


@Component 
@Aspect
public class DataSourceAdvice {

	protected static final Logger logger = LoggerFactory.getLogger(DataSourceAdvice.class);

	@SuppressWarnings("all")
	@Before("execution(* com.hobobe.tailor.dao.persistence.*.*(..))")
	public void before(JoinPoint point) throws Exception {
		//拦截的实体类
		Object target = point.getTarget();
		//拦截的方法名称
		String methodName = point.getSignature().getName();
		//拦截的放参数类型
		Class[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();
		Class[] clazzs = target.getClass().getInterfaces();
		Class clazz = null;
		if (clazzs != null && clazzs.length > 0){
			clazz = clazzs[0];
		}
		
		if (clazz == null) {
			throw new Exception("need set DataSourceType...");
		}
		
		// 拿方法级别的注解
		Method m = clazz.getMethod(methodName, parameterTypes);
		if (m != null && m.isAnnotationPresent(CustAnnotation.class)){
			CustAnnotation ca = m.getAnnotation(CustAnnotation.class);
			if (ca!=null && ca.value()!=null){
				CustomerContextHolder.setCustomerType(ca.value());
				return;
			}
		}
		
		// 拿到类级别的注解
		CustAnnotation can = (CustAnnotation) clazz.getAnnotation(CustAnnotation.class);
		if (can!=null && can.value()!=null){
			CustomerContextHolder.setCustomerType(can.value());
			return;
		}else{
			throw new Exception("need set DataSourceType...");
		}
		
		
	}

}